@{
    ViewData["Title"] = "车间管理";
}

<!-- 直接引入所有必要的CSS和JS文件 -->
<link href="~/libs/scripts/layui-v2.5.6/layui/css/layui.css" rel="stylesheet" />
<script src="~/libs/jquery/jquery.js"></script>
<script src="~/libs/scripts/layui-v2.5.6/layui/layui.js"></script>

<!-- 自定义样式 -->
<style>
    .workshop-container {
        padding: 15px;
        background-color: #f5f5f5;
        min-height: 100vh;
    }
    
    .search-card {
        background: #fff;
        border-radius: 8px;
        box-shadow: 0 2px 8px rgba(0,0,0,0.1);
        margin-bottom: 15px;
    }
    
    .search-form {
        padding: 20px;
        background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
        border-radius: 8px 8px 0 0;
        color: white;
    }
    
    .search-form .layui-form-label {
        color: white;
        font-weight: 500;
    }
    
    .search-form .layui-input, 
    .search-form .layui-select {
        border: 1px solid rgba(255,255,255,0.3);
        background: rgba(255,255,255,0.1);
        color: white;
    }
    
    .search-form .layui-input::placeholder {
        color: rgba(255,255,255,0.7);
    }
    
    .search-form .layui-btn {
        border-radius: 6px;
        font-weight: 500;
        box-shadow: 0 2px 4px rgba(0,0,0,0.2);
    }
    
    .data-card {
        background: #fff;
        border-radius: 8px;
        box-shadow: 0 2px 8px rgba(0,0,0,0.1);
        overflow: hidden;
    }
    
    .data-card-header {
        background: linear-gradient(90deg, #4facfe 0%, #00f2fe 100%);
        padding: 15px 20px;
        color: white;
        font-size: 16px;
        font-weight: 500;
    }
    
    .data-card-body {
        padding: 20px;
    }
    
    .action-bar {
        margin-bottom: 20px;
        padding-bottom: 15px;
        border-bottom: 1px solid #eee;
    }
    
    .action-bar .layui-btn {
        border-radius: 6px;
        font-weight: 500;
        box-shadow: 0 2px 4px rgba(0,0,0,0.1);
        margin-right: 10px;
    }
    
    .layui-table-header {
        background: #f8f9fa;
    }
    
    .layui-table th {
        background: #f8f9fa;
        color: #333;
        font-weight: 600;
        border-bottom: 2px solid #dee2e6;
    }
    
    .layui-table tbody tr:hover {
        background-color: #f0f7ff;
    }
    
    .status-loading, .status-empty {
        background: white;
        border-radius: 8px;
        margin: 20px 0;
        padding: 40px;
        text-align: center;
        color: #666;
    }
    
    .status-loading i, .status-empty i {
        font-size: 48px;
        color: #ccc;
        margin-bottom: 15px;
    }
    
    .status-loading p, .status-empty p {
        font-size: 16px;
        margin: 0;
    }
    
    /* 表格斑马纹效果 */
    .layui-table tbody tr:nth-child(even) {
        background-color: #fafafa;
    }
    
    /* 状态标签样式优化 */
    .status-badge {
        display: inline-block;
        padding: 4px 12px;
        border-radius: 12px;
        font-size: 12px;
        font-weight: 500;
    }
    
    .status-enabled {
        background: #d4edda;
        color: #155724;
        border: 1px solid #c3e6cb;
    }
    
    .status-disabled {
        background: #f8d7da;
        color: #721c24;
        border: 1px solid #f5c6cb;
    }
    
    /* 操作按钮样式优化 */
    .action-btn {
        margin-right: 5px;
        border-radius: 4px;
        font-size: 12px;
    }
</style>

<div class="workshop-container">
    <!-- 搜索区域 -->
    <div class="search-card">
        <div class="search-form">
            <form class="layui-form" lay-filter="searchForm" id="searchForm">
                <div class="layui-row layui-col-space10">
                    <div class="layui-col-md3">
                        <div class="layui-form-item">
                            <label class="layui-form-label">车间编码</label>
                            <div class="layui-input-block">
                                <input type="text" name="code" placeholder="请输入车间编码" autocomplete="off" class="layui-input">
                            </div>
                        </div>
                    </div>
                    <div class="layui-col-md3">
                        <div class="layui-form-item">
                            <label class="layui-form-label">车间名称</label>
                            <div class="layui-input-block">
                                <input type="text" name="name" placeholder="请输入车间名称" autocomplete="off" class="layui-input">
                            </div>
                        </div>
                    </div>
                    <div class="layui-col-md3">
                        <div class="layui-form-item">
                            <label class="layui-form-label">启用状态</label>
                            <div class="layui-input-block">
                                <select name="isEnable" lay-filter="isEnable">
                                    <option value="">全部状态</option>
                                    <option value="true">启用</option>
                                    <option value="false">禁用</option>
                                </select>
                            </div>
                        </div>
                    </div>
                    <div class="layui-col-md3">
                        <div class="layui-form-item">
                            <div class="layui-input-block" style="margin-left: 0;">
                                <button class="layui-btn layui-btn-normal" lay-submit lay-filter="searchBtn">
                                    <i class="layui-icon layui-icon-search"></i> 搜索
                                </button>
                                <button type="button" class="layui-btn layui-btn-primary" id="resetBtn">
                                    <i class="layui-icon layui-icon-refresh"></i> 重置
                                </button>
                            </div>
                        </div>
                    </div>
                </div>
            </form>
        </div>
    </div>

    <!-- 数据区域 -->
    <div class="data-card">
        <div class="data-card-header">
            <i class="layui-icon layui-icon-table"></i> 车间列表
        </div>
        <div class="data-card-body">
            <div class="action-bar">
                <button class="layui-btn layui-btn-normal" id="btnAdd" onclick="showAddForm()">
                    <i class="layui-icon layui-icon-add-1"></i> 新增车间
                </button>
                <button class="layui-btn layui-btn-primary" id="btnRefresh" onclick="refreshTable()">
                    <i class="layui-icon layui-icon-refresh-1"></i> 刷新数据
                </button>
                <button class="layui-btn layui-btn-warm" id="btnExport" onclick="exportData()">
                    <i class="layui-icon layui-icon-export"></i> 导出数据
                </button>
            </div>
            
            <table id="workshopTable" lay-filter="workshopTable"></table>
            
            <!-- 表格加载状态显示 -->
            <div id="tableLoading" class="status-loading" style="display: none;">
                <i class="layui-icon layui-icon-loading layui-anim layui-anim-rotate layui-anim-loop"></i>
                <p>数据加载中，请稍候...</p>
            </div>
            
            <!-- 无数据状态显示 -->
            <div id="tableEmpty" class="status-empty" style="display: none;">
                <i class="layui-icon layui-icon-face-cry"></i>
                <p>暂无数据，点击"新增车间"添加第一条记录</p>
            </div>
        </div>
    </div>
</div>

<!-- 表格操作列模板 -->
<script type="text/html" id="tableToolbar">
    <a class="layui-btn layui-btn-normal layui-btn-xs action-btn" lay-event="edit" title="编辑">
        <i class="layui-icon layui-icon-edit"></i>
    </a>
    <a class="layui-btn layui-btn-danger layui-btn-xs action-btn" lay-event="del" title="删除">
        <i class="layui-icon layui-icon-delete"></i>
    </a>
</script>

<!-- 是否启用模板 -->
<script type="text/html" id="enableTpl">
    {{# if(d.isEnable){ }}
    <span class="status-badge status-enabled">启用</span>
    {{# } else { }}
    <span class="status-badge status-disabled">禁用</span>
    {{# } }}
</script>

<!-- 车间规模模板 -->
<script type="text/html" id="sizeTpl">
    {{# if(d.workshopSize && d.workshopSize !== '0'){ }}
    <span style="color: #1890ff; font-weight: 500;">{{d.workshopSize}}㎡</span>
    {{# } else { }}
    <span style="color: #ccc;">未设置</span>
    {{# } }}
</script>

<!-- 添加车间表单模板 -->
<div id="addFormTemplate" style="display: none;">
    <div style="padding: 25px;">
        <div class="layui-form" lay-filter="addWorkshopForm">
            <div class="layui-row layui-col-space15">
                <div class="layui-col-md12">
                    <div class="layui-form-item">
                        <label class="layui-form-label" style="color: #ff5722; font-weight: 600;">
                            <i class="layui-icon layui-icon-required" style="color: #ff5722;"></i> 车间编码
                        </label>
                        <div class="layui-input-block" style="display: flex; align-items: center;">
                            <input type="text" name="Code" placeholder="请输入车间编码" autocomplete="off" class="layui-input" style="flex: 1;">
                            <div style="margin-left: 15px; display: flex; align-items: center;">
                                <input type="checkbox" name="AutoGenerate" id="autoGenerateCode" lay-skin="switch" lay-text="开|关" title="自动生成">
                                <span style="margin-left: 8px; color: #666; font-size: 13px;">自动生成</span>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="layui-col-md12">
                    <div class="layui-form-item">
                        <label class="layui-form-label" style="color: #ff5722; font-weight: 600;">
                            <i class="layui-icon layui-icon-required" style="color: #ff5722;"></i> 车间名称
                        </label>
                        <div class="layui-input-block">
                            <input type="text" name="Name" placeholder="请输入车间名称" autocomplete="off" class="layui-input">
                        </div>
                    </div>
                </div>
                <div class="layui-col-md6">
                    <div class="layui-form-item">
                        <label class="layui-form-label">车间规模</label>
                        <div class="layui-input-block">
                            <div style="display: flex; align-items: center;">
                                <button type="button" id="decreaseArea" class="layui-btn layui-btn-primary layui-btn-sm" style="border-radius: 4px 0 0 4px;">
                                    <i class="layui-icon layui-icon-subtraction"></i>
                                </button>
                                <input type="number" name="WorkshopSize" value="0" class="layui-input" style="width: 80px; text-align: center; border-radius: 0;">
                                <button type="button" id="increaseArea" class="layui-btn layui-btn-primary layui-btn-sm" style="border-radius: 0 4px 4px 0;">
                                    <i class="layui-icon layui-icon-addition"></i>
                                </button>
                                <span style="margin-left: 8px; color: #666;">㎡</span>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="layui-col-md6">
                    <div class="layui-form-item">
                        <label class="layui-form-label">负责人</label>
                        <div class="layui-input-block">
                            <input type="text" name="WorkshopPerson" placeholder="请输入负责人" autocomplete="off" class="layui-input">
                        </div>
                    </div>
                </div>
                <div class="layui-col-md12">
                    <div class="layui-form-item">
                        <label class="layui-form-label" style="color: #ff5722; font-weight: 600;">
                            <i class="layui-icon layui-icon-required" style="color: #ff5722;"></i> 是否启用
                        </label>
                        <div class="layui-input-block">
                            <input type="radio" name="IsEnable" value="true" title="启用" checked>
                            <input type="radio" name="IsEnable" value="false" title="禁用">
                        </div>
                    </div>
                </div>
                <div class="layui-col-md12">
                    <div class="layui-form-item">
                        <label class="layui-form-label">备注描述</label>
                        <div class="layui-input-block">
                            <textarea name="Description" placeholder="请输入备注描述" class="layui-textarea" rows="3"></textarea>
                        </div>
                    </div>
                </div>
            </div>
            <input type="hidden" name="Id" value="0">
            <input type="hidden" name="ParentId" value="0">
            <input type="hidden" name="IsDeleted" value="false">
            <input type="hidden" name="Index" value="0">
        </div>
    </div>
</div>

<script>
    // 全局变量，确保在各个函数中都可访问
    var table, form, layer, $;
    
    // 页面加载完成后执行
    window.onload = function() {
        console.log("页面加载完成");
        
        // 使用layui模块
        layui.use(['table', 'form', 'layer'], function () {
            console.log("layui模块加载完成");
            
            table = layui.table;
            form = layui.form;
            layer = layui.layer;
            $ = layui.$;

            // 初始化表格
            initTable();
            
            // 绑定搜索事件
            bindSearchEvent();
            
            // 绑定重置事件
            bindResetEvent();
            
            // 绑定工具条事件
            bindToolbarEvent();
            
            // 显示版本信息，便于调试
            console.log("jQuery版本:", $.fn.jquery);
            console.log("Layui版本:", layui.v);
        });
    };
    
    // 全局错误处理，用于调试
    window.onerror = function(message, source, lineno, colno, error) {
        console.error("全局错误:", message);
        console.error("出错脚本:", source);
        console.error("行号:", lineno);
        console.error("列号:", colno);
        console.error("错误对象:", error);
        return true;
    };
    
    // AJAX全局错误处理
    $(document).ajaxError(function(event, jqXHR, ajaxSettings, thrownError) {
        console.error("AJAX请求失败:", ajaxSettings.url);
        console.error("状态码:", jqXHR.status);
        console.error("错误信息:", thrownError);
        console.error("响应文本:", jqXHR.responseText);
    });
    
    // 初始化表格
    function initTable() {
        console.log("开始初始化表格");
        
        // 显示加载状态
        $('#tableLoading').show();
        $('#tableEmpty').hide();
        
        table.render({
            elem: '#workshopTable',
            url: '/ProductionSystem/Workshop/GetWorkshops',
            method: 'get',
            page: {
                layout: ['count', 'prev', 'page', 'next', 'limit', 'skip'],
                prev: '上一页',
                next: '下一页',
                groups: 5,
                theme: '#1890ff'
            },
            limit: 15, // 每页显示的条数
            limits: [10, 15, 20, 50, 100], // 每页条数的选择项
            loading: true,
            even: true, // 开启隔行背景
            size: 'lg', // 表格尺寸
            cols: [[
                { type: 'checkbox', fixed: 'left', width: 50 },
                { field: 'code', title: '车间编码', width: 140, sort: true, templet: function(d) {
                    return '<span style="color: #1890ff; font-weight: 500;">' + (d.code || '') + '</span>';
                }},
                { field: 'name', title: '车间名称', width: 150, sort: true, templet: function(d) {
                    return '<span style="font-weight: 500;">' + (d.name || '') + '</span>';
                }},
                { field: 'workshopSize', title: '车间规模', width: 120, align: 'center', templet: '#sizeTpl' },
                { field: 'workshopPerson', title: '负责人', width: 120, align: 'center', templet: function(d) {
                    return d.workshopPerson ? '<span style="color: #52c41a;">' + d.workshopPerson + '</span>' : '<span style="color: #ccc;">未指定</span>';
                }},
                { field: 'description', title: '描述', minWidth: 200, templet: function(d) {
                    var desc = d.description || '无';
                    return desc.length > 20 ? '<span title="' + desc + '">' + desc.substring(0, 20) + '...</span>' : desc;
                }},
                { field: 'isEnable', title: '状态', width: 100, align: 'center', templet: '#enableTpl' },
                { title: '操作', toolbar: '#tableToolbar', width: 120, fixed: 'right', align: 'center' }
            ]],
            request: {
                pageName: 'page', // 页码的参数名称
                limitName: 'limit' // 每页数据量的参数名
            },
            parseData: function(res) {
                console.log("解析表格数据:", res);
                
                // 检查返回的数据格式并进行转换
                if (res.code === 0) {
                    var processedData = [];
                    
                    // 确保data是数组
                    if (res.data && Array.isArray(res.data)) {
                        processedData = res.data.map(function(item) {
                            console.log("处理数据项:", item);
                            
                            // 确保字段名称正确
                            return {
                                id: item.id,
                                code: item.code,
                                name: item.name,
                                workshopSize: item.workshopSize,
                                workshopPerson: item.workshopPerson,
                                description: item.description,
                                isEnable: item.isEnable
                            };
                        });
                    }
                    
                    console.log("处理后的数据:", processedData);
                    
                    return {
                        "code": 0,
                        "msg": res.msg || '',
                        "count": res.count || processedData.length,
                        "data": processedData
                    };
                } else {
                    console.error("服务器返回异常数据:", res);
                    return {
                        "code": 1,
                        "msg": res.msg || "获取数据失败",
                        "count": 0,
                        "data": []
                    };
                }
            },
            response: {
                statusCode: 0, // 规定成功的状态码
                countName: 'count', // 规定数据总数的字段名称
                dataName: 'data' // 规定数据列表的字段名称
            },
            done: function (res, curr, count) {
                console.log("表格加载完成，数据:", res);
                console.log("当前页:", curr, "总数:", count);
                
                // 隐藏加载状态
                $('#tableLoading').hide();
                
                if (res.code !== 0) {
                    console.error("表格加载失败:", res.msg);
                    layer.msg('加载数据失败：' + res.msg, {icon: 2});
                } else if (!res.data || res.data.length === 0) {
                    console.log("表格数据为空");
                    // 显示无数据状态
                    $('#tableEmpty').show();
                } else {
                    console.log("表格数据加载成功，条数:", res.data.length);
                    $('#tableEmpty').hide();
                    layer.msg('数据加载成功，共 ' + count + ' 条记录', {icon: 1, time: 2000});
                }
            }
        });
    }
    
    // 刷新表格数据
    function refreshTable() {
        console.log("刷新表格数据");
        
        // 显示加载状态
        $('#tableLoading').show();
        $('#tableEmpty').hide();
        
        table.reload('workshopTable', {
            where: {}, // 可以传递查询条件
            page: {
                curr: 1 // 重新从第 1 页开始
            },
            done: function(res) {
                // 隐藏加载状态
                $('#tableLoading').hide();
                
                if (res.code !== 0) {
                    layer.msg('刷新数据失败：' + res.msg, {icon: 2});
                } else if (res.data && res.data.length === 0) {
                    // 显示无数据状态
                    $('#tableEmpty').show();
                } else {
                    layer.msg('数据刷新成功', {icon: 1, time: 2000});
                }
            }
        });
    }
    
    // 绑定搜索事件
    function bindSearchEvent() {
        form.on('submit(searchBtn)', function (data) {
            console.log("执行搜索，条件:", data.field);
            
            // 显示加载状态
            $('#tableLoading').show();
            $('#tableEmpty').hide();
            
            table.reload('workshopTable', {
                where: data.field,
                page: { curr: 1 },
                done: function(res) {
                    $('#tableLoading').hide();
                    if (res.code === 0) {
                        if (res.data && res.data.length > 0) {
                            layer.msg('搜索完成，找到 ' + res.count + ' 条记录', {icon: 1, time: 2000});
                        } else {
                            $('#tableEmpty').show();
                            layer.msg('未找到符合条件的记录', {icon: 0, time: 2000});
                        }
                    } else {
                        layer.msg('搜索失败：' + res.msg, {icon: 2});
                    }
                }
            });
            return false;
        });
    }
    
    // 绑定重置事件
    function bindResetEvent() {
        $('#resetBtn').on('click', function() {
            console.log("执行重置操作");
            
            // 重置表单
            document.getElementById('searchForm').reset();
            
            // 重新渲染表单（重置下拉框等组件）
            form.render();
            
            // 重新加载表格数据（不带任何条件）
            $('#tableLoading').show();
            $('#tableEmpty').hide();
            
            table.reload('workshopTable', {
                where: {},
                page: { curr: 1 },
                done: function(res) {
                    $('#tableLoading').hide();
                    if (res.code === 0) {
                        if (res.data && res.data.length > 0) {
                            layer.msg('重置成功，显示全部 ' + res.count + ' 条记录', {icon: 1, time: 2000});
                        } else {
                            $('#tableEmpty').show();
                        }
                    } else {
                        layer.msg('重置失败：' + res.msg, {icon: 2});
                    }
                }
            });
        });
    }
    
    // 绑定工具条事件
    function bindToolbarEvent() {
        table.on('tool(workshopTable)', function (obj) {
            var data = obj.data;
            if (obj.event === 'del') {
                layer.confirm('确定要删除车间 "' + data.name + '" 吗？<br><span style="color: #ff5722;">此操作不可撤销！</span>', {
                    icon: 3,
                    title: '删除确认',
                    btn: ['确定删除', '取消']
                }, function (index) {
                    var loadIndex = layer.load(2, {content: '删除中...'});
                    $.ajax({
                        url: '/ProductionSystem/Workshop/Delete/' + data.id,
                        type: 'POST',
                        success: function (res) {
                            layer.close(loadIndex);
                            if (res.code === 0) {
                                layer.msg('删除成功', {icon: 1});
                                refreshTable();
                            } else {
                                layer.msg(res.msg || '删除失败', {icon: 2});
                            }
                        },
                        error: function(xhr, status, error) {
                            layer.close(loadIndex);
                            console.error("删除失败:", xhr.responseText);
                            layer.msg('删除失败: ' + (xhr.responseJSON?.msg || error), {icon: 2});
                        }
                    });
                    layer.close(index);
                });
            } else if (obj.event === 'edit') {
                showEditForm(data);
            }
        });
    }
    
    // 导出数据功能
    function exportData() {
        layer.msg('导出功能开发中...', {icon: 0, time: 2000});
    }
    
    // 显示添加表单
    function showAddForm() {
        console.log("调用showAddForm函数");
        
        try {
            // 打开弹出层
            var index = layer.open({
                type: 1,
                title: '<i class="layui-icon layui-icon-add-1"></i> 新增车间',
                content: $('#addFormTemplate').html(),
                area: ['600px', '650px'],
                btn: ['<i class="layui-icon layui-icon-ok"></i> 确定', '<i class="layui-icon layui-icon-close"></i> 取消'],
                btnAlign: 'c',
                closeBtn: 1,
                shade: 0.3,
                shadeClose: false,
                yes: function(index, layero) {
                    console.log("点击确定按钮");
                    
                    // 获取表单数据
                    var formData = {
                        Id: 0,
                        Code: $(layero).find('input[name="Code"]').val(),
                        Name: $(layero).find('input[name="Name"]').val(),
                        WorkshopSize: $(layero).find('input[name="WorkshopSize"]').val().toString(),
                        WorkshopPerson: $(layero).find('input[name="WorkshopPerson"]').val(),
                        IsEnable: $(layero).find('input[name="IsEnable"]:checked').val() === 'true',
                        Description: $(layero).find('textarea[name="Description"]').val(),
                        ParentId: 0,
                        IsDeleted: false,
                        Index: 0
                    };
                    
                    // 验证表单
                    if (!formData.Code) {
                        layer.msg('车间编码不能为空', {icon: 2});
                        return;
                    }
                    
                    if (!formData.Name) {
                        layer.msg('车间名称不能为空', {icon: 2});
                        return;
                    }
                    
                    console.log("提交的数据：", JSON.stringify(formData));
                    
                    // 发送请求
                    var loadIndex = layer.load(2, {content: '保存中...'});
                    $.ajax({
                        url: '/ProductionSystem/Workshop/Add',
                        type: 'POST',
                        contentType: 'application/json',
                        data: JSON.stringify(formData),
                        success: function(res) {
                            layer.close(loadIndex);
                            if (res.code === 0) {
                                layer.close(index);
                                layer.msg('新增成功', {icon: 1});
                                refreshTable();
                            } else {
                                layer.msg(res.msg || '新增失败', {icon: 2});
                            }
                        },
                        error: function(xhr, status, error) {
                            layer.close(loadIndex);
                            console.error("AJAX错误：", xhr.responseText);
                            console.error("状态码：", xhr.status);
                            console.error("错误信息：", error);
                            console.error("提交的数据：", JSON.stringify(formData));
                            var errorMsg = '新增失败';
                            if (xhr.responseJSON && xhr.responseJSON.msg) {
                                errorMsg = xhr.responseJSON.msg;
                            }
                            layer.msg(errorMsg + '（状态码：' + xhr.status + '）', {icon: 2});
                        }
                    });
                },
                success: function(layero, index) {
                    console.log("弹出层显示成功");
                    
                    // 渲染表单
                    form.render(null, 'addWorkshopForm');
                    
                    // 自动生成编码
                    $(layero).find('#autoGenerateCode').on('change', function() {
                        if ($(this).prop('checked')) {
                            $(layero).find('input[name="Code"]').attr('disabled', true);
                            // 生成一个临时编码
                            var randomCode = 'WS' + new Date().getFullYear() + (Math.floor(Math.random() * 10000)).toString().padStart(4, '0');
                            $(layero).find('input[name="Code"]').val(randomCode);
                        } else {
                            $(layero).find('input[name="Code"]').attr('disabled', false);
                            $(layero).find('input[name="Code"]').val('');
                        }
                    });
                    
                    // 增加/减少面积
                    $(layero).find('#decreaseArea').on('click', function() {
                        var input = $(layero).find('input[name="WorkshopSize"]');
                        var value = parseInt(input.val()) || 0;
                        if (value > 0) {
                            input.val(value - 10);
                        }
                    });
                    
                    $(layero).find('#increaseArea').on('click', function() {
                        var input = $(layero).find('input[name="WorkshopSize"]');
                        var value = parseInt(input.val()) || 0;
                        input.val(value + 10);
                    });
                }
            });
            
            console.log("弹出层索引：", index);
        } catch (error) {
            console.error("显示弹出层出错：", error);
            layer.msg("显示弹出层出错：" + error.message, {icon: 2});
        }
    }

    // 显示编辑表单
    function showEditForm(data) {
        console.log("调用showEditForm函数，data:", data);
        
        // 创建编辑表单内容
        var content = 
            '<div style="padding: 25px;">' +
                '<div class="layui-form" lay-filter="editWorkshopForm">' +
                    '<div class="layui-row layui-col-space15">' +
                        '<div class="layui-col-md12">' +
                            '<div class="layui-form-item">' +
                                '<label class="layui-form-label" style="color: #ff5722; font-weight: 600;"><i class="layui-icon layui-icon-required" style="color: #ff5722;"></i> 车间编码</label>' +
                                '<div class="layui-input-block">' +
                                    '<input type="text" name="Code" value="' + (data.code || '') + '" placeholder="请输入车间编码" autocomplete="off" class="layui-input">' +
                                '</div>' +
                            '</div>' +
                        '</div>' +
                        '<div class="layui-col-md12">' +
                            '<div class="layui-form-item">' +
                                '<label class="layui-form-label" style="color: #ff5722; font-weight: 600;"><i class="layui-icon layui-icon-required" style="color: #ff5722;"></i> 车间名称</label>' +
                                '<div class="layui-input-block">' +
                                    '<input type="text" name="Name" value="' + (data.name || '') + '" placeholder="请输入车间名称" autocomplete="off" class="layui-input">' +
                                '</div>' +
                            '</div>' +
                        '</div>' +
                        '<div class="layui-col-md6">' +
                            '<div class="layui-form-item">' +
                                '<label class="layui-form-label">车间规模</label>' +
                                '<div class="layui-input-block">' +
                                    '<div style="display: flex; align-items: center;">' +
                                        '<button type="button" id="decreaseArea" class="layui-btn layui-btn-primary layui-btn-sm" style="border-radius: 4px 0 0 4px;"><i class="layui-icon layui-icon-subtraction"></i></button>' +
                                        '<input type="number" name="WorkshopSize" value="' + (data.workshopSize || 0) + '" class="layui-input" style="width: 80px; text-align: center; border-radius: 0;">' +
                                        '<button type="button" id="increaseArea" class="layui-btn layui-btn-primary layui-btn-sm" style="border-radius: 0 4px 4px 0;"><i class="layui-icon layui-icon-addition"></i></button>' +
                                        '<span style="margin-left: 8px; color: #666;">㎡</span>' +
                                    '</div>' +
                                '</div>' +
                            '</div>' +
                        '</div>' +
                        '<div class="layui-col-md6">' +
                            '<div class="layui-form-item">' +
                                '<label class="layui-form-label">负责人</label>' +
                                '<div class="layui-input-block">' +
                                    '<input type="text" name="WorkshopPerson" value="' + (data.workshopPerson || '') + '" placeholder="请输入负责人" autocomplete="off" class="layui-input">' +
                                '</div>' +
                            '</div>' +
                        '</div>' +
                        '<div class="layui-col-md12">' +
                            '<div class="layui-form-item">' +
                                '<label class="layui-form-label" style="color: #ff5722; font-weight: 600;"><i class="layui-icon layui-icon-required" style="color: #ff5722;"></i> 是否启用</label>' +
                                '<div class="layui-input-block">' +
                                    '<input type="radio" name="IsEnable" value="true" title="启用" ' + (data.isEnable !== false ? 'checked' : '') + '>' +
                                    '<input type="radio" name="IsEnable" value="false" title="禁用" ' + (data.isEnable === false ? 'checked' : '') + '>' +
                                '</div>' +
                            '</div>' +
                        '</div>' +
                        '<div class="layui-col-md12">' +
                            '<div class="layui-form-item">' +
                                '<label class="layui-form-label">备注描述</label>' +
                                '<div class="layui-input-block">' +
                                    '<textarea name="Description" placeholder="请输入备注描述" class="layui-textarea" rows="3">' + (data.description || '') + '</textarea>' +
                                '</div>' +
                            '</div>' +
                        '</div>' +
                    '</div>' +
                    '<input type="hidden" name="Id" value="' + (data.id || 0) + '">' +
                    '<input type="hidden" name="ParentId" value="0">' +
                    '<input type="hidden" name="IsDeleted" value="false">' +
                    '<input type="hidden" name="Index" value="0">' +
                '</div>' +
            '</div>';
        
        // 打开弹出层
        layer.open({
            type: 1,
            title: '<i class="layui-icon layui-icon-edit"></i> 编辑车间',
            content: content,
            area: ['600px', '650px'],
            btn: ['<i class="layui-icon layui-icon-ok"></i> 确定', '<i class="layui-icon layui-icon-close"></i> 取消'],
            btnAlign: 'c',
            closeBtn: 1,
            shade: 0.3,
            shadeClose: false,
            yes: function(index, layero) {
                // 获取表单数据
                var formData = {
                    Id: data.id,
                    Code: $(layero).find('input[name="Code"]').val(),
                    Name: $(layero).find('input[name="Name"]').val(),
                    WorkshopSize: $(layero).find('input[name="WorkshopSize"]').val().toString(),
                    WorkshopPerson: $(layero).find('input[name="WorkshopPerson"]').val(),
                    IsEnable: $(layero).find('input[name="IsEnable"]:checked').val() === 'true',
                    Description: $(layero).find('textarea[name="Description"]').val(),
                    ParentId: 0,
                    IsDeleted: false,
                    Index: 0
                };
                
                // 验证表单
                if (!formData.Code) {
                    layer.msg('车间编码不能为空', {icon: 2});
                    return;
                }
                
                if (!formData.Name) {
                    layer.msg('车间名称不能为空', {icon: 2});
                    return;
                }
                
                console.log("提交的编辑数据：", JSON.stringify(formData));
                
                // 发送请求
                var loadIndex = layer.load(2, {content: '保存中...'});
                $.ajax({
                    url: '/ProductionSystem/Workshop/Update',
                    type: 'POST',
                    contentType: 'application/json',
                    data: JSON.stringify(formData),
                    success: function(res) {
                        layer.close(loadIndex);
                        if (res.code === 0) {
                            layer.close(index);
                            layer.msg('更新成功', {icon: 1});
                            refreshTable();
                        } else {
                            layer.msg(res.msg || '更新失败', {icon: 2});
                        }
                    },
                    error: function(xhr, status, error) {
                        layer.close(loadIndex);
                        console.error("AJAX错误：", xhr.responseText);
                        console.error("状态码：", xhr.status);
                        console.error("错误信息：", error);
                        console.error("提交的数据：", JSON.stringify(formData));
                        var errorMsg = '更新失败';
                        if (xhr.responseJSON && xhr.responseJSON.msg) {
                            errorMsg = xhr.responseJSON.msg;
                        }
                        layer.msg(errorMsg + '（状态码：' + xhr.status + '）', {icon: 2});
                    }
                });
            },
            success: function(layero, index) {
                // 渲染表单
                form.render(null, 'editWorkshopForm');
                
                // 增加/减少面积
                $(layero).find('#decreaseArea').on('click', function() {
                    var input = $(layero).find('input[name="WorkshopSize"]');
                    var value = parseInt(input.val()) || 0;
                    if (value > 0) {
                        input.val(Math.max(0, value - 10));
                    }
                });
                
                $(layero).find('#increaseArea').on('click', function() {
                    var input = $(layero).find('input[name="WorkshopSize"]');
                    var value = parseInt(input.val()) || 0;
                    input.val(value + 10);
                });
            }
        });
    }
</script> 